import {
  getSingleAccountList,
  singleChange,
} from '@/services/production-center';
import { accMul } from '@/utils/math';
import { InfoCircleOutlined, UploadOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';
import {
  Button,
  Form,
  Input,
  Radio,
  Skeleton,
  Tabs,
  Upload,
  UploadProps,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
import ConfirmModal from './components/ConfirmModal';
import ErrorModal from './components/ErrorModal';
import RechargeModal from './components/RechargeModal';
import Tip from './components/Tip';

const TabsData = [
  {
    label: '单笔转账',
    key: 'single',
  },
  {
    label: '批量转账',
    key: 'batch',
  },
];

const ACSChange = () => {
  const [safeAliPayAccount, setSafeAliPayAccount] = useState<
    Array<{
      alipayNickName: string;
      businessName: string;
      bookBalance: string;
    }>
  >([]);
  const [openCharge, setOpenCharge] = useState(false);
  const [changeType, setChangeType] = useState('single');
  const [paramsData, setParamsData] = useState({
    alipayNickName: '',
    identity: '',
    name: '',
    remark: '',
    transAmount: 0,
    orderTitle: '酬劳发放',
    type: '1',
  });
  const { initialState } = useModel('@@initialState');
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [importErrorMessage, setImportErrorMessage] = useState('');
  const [errorDataSource, setErrorDataSource] = useState([]);
  const [fileList, setFileList] = useState<any>([]);

  const [changeResData, setChangeResData] = useState(undefined);
  const [title, setTitle] = useState('请核对金额和笔数');
  const [initLoading, setInitLoading] = useState(false);
  const getInitData = () => {
    setInitLoading(true);
    getSingleAccountList({
      signStatus: 'NORMAL',
    })
      .then((res: any) => {
        if (res.success) {
          setSafeAliPayAccount(res.data || []);
          setParamsData({
            ...paramsData,
            alipayNickName: res.data[0]?.alipayNickName,
          });
        } else {
          message.error(res.resultMessage);
        }
      })
      .finally(() => {
        setInitLoading(false);
      });
  };

  useEffect(() => {
    getInitData();
  }, []);

  const renderAccountArea = () => {
    if (!safeAliPayAccount.length) {
      return (
        <Button
          type="primary"
          onClick={() => {
            history.push('/account-center/sign-manager/account-sign');
          }}
        >
          去签约
        </Button>
      );
    }
    return (
      <Radio.Group
        value={paramsData.alipayNickName}
        className="flex items-center flex-wrap min-h-[62px] gap-4"
        onChange={(e) => {
          setParamsData({
            ...paramsData,
            alipayNickName: e.target.value,
          });
        }}
      >
        {safeAliPayAccount.map((item, index) => {
          return (
            <div
              key={index}
              className={`border min-w-[340px] ${item.alipayNickName === paramsData.alipayNickName
                  ? 'border-[#00bdff]'
                  : ''
                }`}
            >
              <Radio
                className="h-[60px] flex items-center p-6"
                value={item.alipayNickName}
              >
                <div className="flex">
                  <div>{item.alipayNickName}</div>
                  <div>(余额：¥ {item.bookBalance})</div>
                </div>
                <div>{item.businessName}</div>
              </Radio>
            </div>
          );
        })}
      </Radio.Group>
    );
  };

  const uploadProp: UploadProps = {
    name: 'file',
    action: '/api/merchant/excel/import-safe-pay-trans',
    data: {
      alipayNickName: paramsData.alipayNickName,
      type: paramsData.type
    },
    headers: {
      authorization: 'authorization-text',
    },
    multiple: true,
    fileList: fileList,
    onChange(info) {
      setFileList(info.fileList);

      if (info.file.status === 'uploading') {
        setImportErrorMessage('');
      }
      if (info.file.status === 'done') {
        console.log('info', info);
        if (info.file.response.resultCode === 'val.parameter_illegal') {
          message.error(info.file.response.resultMessage);
          setImportErrorMessage(info.file.response.resultMessage);
          setFileList([]);
          return;
        }
        if (info.file.response.resultCode === 'val.excel_data_illegal') {
          setErrorDataSource(JSON.parse(info.file.response.resultMessage));
          return;
        }
        if (info.file.response.success) {
          setChangeResData(info.file.response.data);
          setTitle('导入成功，请核对金额和笔数');
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };

  const renderStep5 = () => {
    if (changeType !== 'single') {
      return (
        <div className="mt-6 flex">
          <div className="flex-[0.2]">Step:5 上传批量转账表格：</div>
          <div className="flex-1 flex gap-3">
            {safeAliPayAccount.length > 0 ? (
              <Upload {...uploadProp} accept=".xls,.xlsx">
                <Button type="primary" icon={<UploadOutlined />}>
                  点击上传表格
                </Button>
              </Upload>
            ) : (
              <Button
                type="primary"
                icon={<UploadOutlined />}
                onClick={() => {
                  message.info('请先签约账户');
                }}
              >
                点击上传表格
              </Button>
            )}
            <Button
              href={`${paramsData.type === '1'
                  ? '/api/merchant/excel/safe-pay-trans-tpl'
                  : '/api/merchant/excel/safe-pay-bank-trans-tpl'
                }`}
            >
              下载批量转账到{paramsData.type === '1' ? '支付宝' : '银行卡'}
              表格模版
            </Button>
          </div>
        </div>
      );
    }
    return (
      <div className="my-6">
        <div>Step:5 填写转账信息：</div>
        <Form
          className="pl-40"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 5 }}
        >
          <Form.Item
            rules={[
              {
                required: true,
                message: `${paramsData.type === '1'
                    ? '请输入收款人支付宝账号'
                    : '请输入收款人银行卡号'
                  }`,
              },
            ]}
            label={`${paramsData.type === '1' ? '收款人支付宝账号' : '收款人银行卡号'
              }`}
            name="identity"
          >
            <Input
              placeholder={`${paramsData.type === '1'
                  ? '请输入收款人支付宝账号'
                  : '请输入收款人银行卡号'
                }`}
            />
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: '请输入收款人真实姓名' }]}
            label="收款人真实姓名"
            name="name"
          >
            <Input placeholder="请输入收款人真实姓名" />
          </Form.Item>
          <Form.Item
            rules={[{ required: true, message: '请输入收款金额' }]}
            label="收款金额"
            name="transAmount"
          >
            <Input placeholder="请输入收款金额" />
          </Form.Item>
          <Form.Item label="转账备注" name="remark">
            <Input placeholder="转账备注" />
          </Form.Item>
        </Form>
      </div>
    );
  };

  return (
    <div className="bg-white p-4 h-full">
      <Tabs
        items={TabsData}
        onChange={(key) => {
          setChangeType(key);
        }}
      />
      <div className="mb-4 flex justify-between">
        <div>Step1: 选择转账账户：</div>
        <div
          className="text-[#00bdff] cursor-pointer"
          onClick={() => {
            setOpenCharge(true);
          }}
        >
          备付金账户余额不足？前往充值
        </div>
      </div>
      <div>
        <Skeleton active loading={initLoading}>
          {renderAccountArea()}
        </Skeleton>
      </div>
      <div className="py-3 flex items-center border-dashed border-b gap-3">
        {/* <div>
          <span className="bg-orange-400 text-white py-1 px-3 rounded-lg">
            当日转账剩余额度
          </span>
          ：0元
        </div>
        <div>
          <span className="bg-orange-400 text-white py-1 px-3 rounded-lg">
            当月转账剩余额度
          </span>
          ：0元
        </div> */}
      </div>
      {/* step2 */}
      <div className="my-6 flex">
        <div className="flex-[0.2]">Step2: 选择收款账户类型：</div>
        <Radio.Group
          className="flex-1"
          defaultValue={'1'}
          onChange={(e) => {
            setParamsData({
              ...paramsData,
              type: e.target.value,
            });
          }}
        >
          <Radio value={'1'}>到支付宝</Radio>
          <Radio value={'2'}>到银行卡</Radio>
        </Radio.Group>
      </div>
      {/* step3 */}
      <div className="my-6 flex">
        <div className="flex-[0.2]">Step3: 确认转账服务费：</div>
        <div className="flex-1">
          到{paramsData.type === '1' ? '支付宝' : '银行卡'}【
          {initialState?.currentUser?.mode === 'fixed_ratio'
            ? `${accMul(paramsData.type === '1' ? initialState?.currentUser?.serviceRatio : initialState?.currentUser?.bankServiceRatio, 100).toFixed(
              2,
            )}%`
            : `${accMul(
              initialState?.currentUser?.serviceUnitPrice,
              100,
            ).toFixed(2)}%`}
          】
        </div>
      </div>
      {/* Step4 */}
      <div className="flex my-6">
        <div className="flex-[0.2]">Step4: 选择转账用途：</div>
        <Radio.Group
          className="flex-1"
          defaultValue={'酬劳发放'}
          onChange={(e) => {
            setParamsData({
              ...paramsData,
              orderTitle: e.target.value,
            });
          }}
        >
          <Radio value={'酬劳发放'}>酬劳发放</Radio>
          <Radio value={'福利发放'}>福利发放</Radio>
          <Radio value={'佣金结算'}>佣金结算</Radio>
          <Radio value={'用户提现'}>用户提现</Radio>
          <Radio value={'推广佣金'}>推广佣金</Radio>
          <Radio value={'费用报销'}>费用报销</Radio>
          <Radio value={'贷款结算'}>贷款结算</Radio>
        </Radio.Group>
      </div>
      {/* Step5 */}
      {renderStep5()}
      {importErrorMessage && (
        <div className="text-[red] ml-[17%] mt-3">{importErrorMessage}</div>
      )}
      <Tip changeType={changeType} />
      <div className="ml-[17%]">
        {changeType === 'single' && (
          <Button
            type="primary"
            className="my-6"
            loading={loading}
            onClick={async () => {
              if (safeAliPayAccount.length === 0) {
                message.info('请先签约账户');
                return;
              }
              if (changeType === 'single') {
                await form.validateFields();
                const values = form.getFieldsValue();
                setLoading(true);
                singleChange({
                  ...paramsData,
                  ...values,
                })
                  .then((res: any) => {
                    if (res.success) {
                      setChangeResData(res.data);
                    } else {
                      message.error(res.resultMessage);
                    }
                  })
                  .finally(() => {
                    setLoading(false);
                  });
                return;
              }
            }}
          >
            确认转账
          </Button>
        )}
        <div
          className={`flex text-[red] ${changeType === 'single' ? '' : 'mt-6'}`}
        >
          <InfoCircleOutlined />
          <div>
            禁止将支付工具用于黄、赌、毒等国家法律不允许的行业使用，如有发现，将终止合作。
          </div>
        </div>
      </div>
      <RechargeModal
        openCharge={openCharge}
        onCancel={() => {
          setOpenCharge(false);
        }}
        successCallback={() => {
          getInitData();
          setOpenCharge(false);
        }}
        alipayNickName={paramsData.alipayNickName}
      />
      <ErrorModal
        dataSource={errorDataSource}
        onOk={() => {
          setErrorDataSource([]);
          setFileList([]);
        }}
      />
      <ConfirmModal
        title={title}
        changeResData={changeResData}
        currentAliPayName={paramsData.alipayNickName}
        onCancel={() => {
          setChangeResData(undefined);
        }}
      />
    </div>
  );
};

export default ACSChange;
